import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { Input, Rate, Select } from 'antd';
import TagSelect from '@components/tag-select';
import OrgCascader from '@components/org-cascader';
import { ORIGIN_DESC_MAP } from '@util/constants';
import { bindActionCreators } from 'redux';
import { actions as assetManageActions } from '@containers/asset-manage/reducer';
import UserSelect from '@components/user-select';
import { connect } from 'react-redux';
const { Option } = Select;

const infoArr = [
  { key: 'staffOid.telephone', name: '手机号', className: 'telephone' },
  { key: 'staffOid.email', name: '邮箱', className: 'email' },
  { key: 'uyunCMDB.maintenanceTeam', name: '运维团队', className: 'email' },
  { key: 'uyunCMDB.maintenancePerson', name: '运维人员', className: 'email' },
  { key: 'uyunCMDB.resourceApplicant', name: '资源申请人', className: 'email' },
  { key: 'userType', name: '使用者类型', className: 'userType' },
  { key: 'user', name: '使用者', className: 'user' },
  { key: 'owner', name: '组织', className: 'owner' },
  { key: 'asn', name: 'ASN', className: 'asn' },
  { key: 'ispDomain', name: '运营商', className: 'ispDomain' }
];

const renderCustomAttributes = (
  currentDetail,
  customAttributeList,
  onChangeCustomAttributeValue,
  onUpdateSite
) => {
  const customAttributes = _.get(currentDetail, 'customAttributes', []);

  return customAttributeList.map(attr => {
    const attrName = attr.name || '-';
    const attrId = attr._id;
    const value = _.get(_.find(customAttributes, i => i.attributeOid === attrId), 'value', []);
    const options = _.get(attr, 'options', []).map(i => (
      <Select.Option key={i} title={i} value={i}>
        {i}
      </Select.Option>
    ));
    if (attr.type === 'single') {
      // 单选自定义属性
      return (
        <div className="info-item custom-attr" key={attrId}>
          <label title={attrName}>{attrName}</label>
          <Select
            value={value}
            onChange={value => onChangeCustomAttributeValue(attrId, [].concat(value), onUpdateSite)}
          >
            {options}
          </Select>
        </div>
      );
    } else if (attr.type === 'multiple') {
      // 多选自定义属性
      return (
        <div className="info-item custom-attr" key={attrId}>
          <label title={attrName}>{attrName}</label>
          <Select
            mode="multiple"
            value={value}
            onChange={value => onChangeCustomAttributeValue(attrId, value, onUpdateSite)}
          >
            {options}
          </Select>
        </div>
      );
    } else if (attr.type === 'string') {
      // 填空自定义属性
      return (
        <div className="info-item custom-attr" key={attrId}>
          <label title={attrName}>{attrName}</label>
          <Input
            value={value.toString()}
            onChange={e => onChangeCustomAttributeValue(attrId, [e.target.value])}
            onBlur={onUpdateSite}
          />
        </div>
      );
    } else {
      return null;
    }
  });
};

function RightContent(props) {
  const {
    currentDetail,
    onChangeSiteContent,
    onOrgPopupVisibleChange,
    organizationTree,
    searchKeyWordDataType,
    onSelectIndustry,
    allIndustries = [],
    customAttributeList = [],
    onChangeCustomAttributeValue,
    onUpdateSite,
    modules
  } = props;
  const origin = () => {
    const origin_ = _.get(currentDetail, 'origin', []);
    if (typeof origin_ === 'string') {
      return ORIGIN_DESC_MAP[origin_];
    } else if (Array.isArray(origin_)) {
      return origin_.map(e => ORIGIN_DESC_MAP[e]).join('，');
    } else {
      return '-';
    }
  };

  const hasOneDayModule = modules.includes('1day');

  return (
    <div className="right">
      {hasOneDayModule && (
        <div className="info-item risk">
          <label>风险值</label>
          <span>{_.get(currentDetail, 'risk') || 0}</span>
        </div>
      )}

      <div className="info-item weight">
        <label>权重</label>
        <Rate
          value={_.get(currentDetail, 'weight') || 1}
          onChange={weight => onChangeSiteContent('weight', weight || 1, onUpdateSite)}
        />
      </div>
      <div className="info-item tag">
        <label>标签</label>
        <TagSelect
          selected={_.get(currentDetail, 'tag_oids', [])}
          onChange={tags => onChangeSiteContent('tag_oids', tags, onUpdateSite)}
        />
      </div>
      <div className="info-item organization">
        <label>所属部门</label>
        <OrgCascader
          onOrgPopupVisibleChange={onOrgPopupVisibleChange}
          options={organizationTree}
          getPopupContainer={() => document.body}
          onChange={org => onChangeSiteContent('organizationPaths', org, onUpdateSite)}
          value={[].concat(_.get(currentDetail, 'organizationPaths', []))}
        />
      </div>
      <div className="info-item staff">
        <label>管理员</label>
        <UserSelect
          defaultValue={_.get(currentDetail, 'staffOid.nickname')}
          onChange={staffOid => onChangeSiteContent('staffOid._id', staffOid, onUpdateSite)}
        />
      </div>
      {infoArr.map(item => {
        const { key, name, className } = item;
        let arr = ['userType', 'user', 'owner', 'asn', 'ispDomain'];
        if (key.includes('uyunCMDB') || arr.includes(key)) {
          return _.get(currentDetail, key) ? (
            <div className={`info-item ${className}`} key={key}>
              <label>{name}</label>
              <span>{_.get(currentDetail, key)}</span>
            </div>
          ) : null;
        } else {
          return (
            <div className={`info-item ${className}`} key={key}>
              <label>{name}</label>
              <span>{_.get(currentDetail, key, '-') || '-'}</span>
            </div>
          );
        }
      })}
      <div className="info-item organization">
        <label>行业</label>
        <Select
          showSearch
          getPopupContainer={triggerNode => triggerNode.parentNode}
          onChange={value => onChangeSiteContent('industry', value, onUpdateSite)}
          onSearch={value => onSelectIndustry(value)}
          placeholder="请选择行业"
          value={_.get(currentDetail, 'industry')}
          filterOption={(input, option) => {
            if (option && option.props && option.props.title) {
              return option.props.title === input || option.props.title.indexOf(input) !== -1;
            } else {
              return true;
            }
          }}
        >
          {searchKeyWordDataType &&
          _.findIndex(allIndustries, ['name', searchKeyWordDataType]) === -1 ? (
              <Option value={searchKeyWordDataType}>
                {searchKeyWordDataType}
                <span style={{ color: 'red' }}>（新增）</span>
              </Option>
            ) : 
            ''
          }
          {allIndustries.map(item => {
            return (
              <Option key={item._id} value={item._id} title={item.name}>
                {item.name}
              </Option>
            );
          })}
        </Select>
      </div>
      {_.get(currentDetail, 'scene') && (
        <div className="info-item scene">
          <label>应用场景</label>
          <span>{_.get(currentDetail, 'scene', '-')}</span>
        </div>
      )}
      {renderCustomAttributes(
        currentDetail,
        customAttributeList,
        onChangeCustomAttributeValue,
        onUpdateSite
      )}
      <div className="info-item origin">
        <label>来源</label>
        <span>{origin() || '-'}</span>
      </div>
      {_.get(currentDetail, 'uyunCMDB.extraInfo') && (
        <div className="info-item origin">
          <label>备注</label>
          <span>{_.get(currentDetail, 'uyunCMDB.extraInfo')}</span>
        </div>
      )}

      <div className="info-item created-at">
        <label>创建时间</label>
        <span>{_.get(currentDetail, 'created') || '-'}</span>
      </div>
      <div className="info-item updated-at">
        <label>更新时间</label>
        <span>{_.get(currentDetail, 'updated') || '-'}</span>
      </div>
    </div>
  );
}
RightContent.propTypes = {
  currentDetail: PropTypes.object.isRequired,
  onChangeSiteContent: PropTypes.func.isRequired,
  onOrgPopupVisibleChange: PropTypes.func,
  onSelectIndustry: PropTypes.func,
  renderCustomAttributes: PropTypes.func,
  onUpdateSite: PropTypes.func,
  onChangeCustomAttributeValue: PropTypes.func,
  organizationTree: PropTypes.object,
  staffList: PropTypes.array,
  allIndustries: PropTypes.array,
  customAttributeList: PropTypes.array,
  searchKeyWordDataType: PropTypes.string,
  modules: PropTypes.array
};

RightContent.defaultProps = {
  currentDetail: {},
  onChangeSiteContent: () => {},
  modules: []
};

const mapStateToProps = state => {
  return {
    organizationTree: _.get(state, 'assetManage.organizationTree', []),
    staffList: _.get(state, 'assetManage.staffList', []),
    customAttributeList: _.get(state, 'assetManage.customAttributeList', []),
    allIndustries: _.get(state, 'assetManage.allIndustries', []),
    modules: _.get(state, 'auth.cert.modules', [])
  };
};

const mapDispatchToProps = dispatch => {
  return {
    ...bindActionCreators(assetManageActions, dispatch)
  };
};
export default connect(
  mapStateToProps,
  mapDispatchToProps
)(RightContent);
